package lib.db.pool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Properties;

import com.mysql.jdbc.Driver;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlPooledConnection;
public class MySQLConnection {	
	private ConnectionParameters connParam = null;
	
	public ConnectionParameters getConnParam() {
		return connParam;
	}

	public void setConnParam(ConnectionParameters connParam) {
		this.connParam = connParam;
	}
	static Hashtable<String, ConnectionParameters> hashTable=null;
	static{
		hashTable= MySQLGetConnection.loadData();
	}

	public MySQLConnection(String poolName){
		try{			
			this.setConnParam((ConnectionParameters)hashTable.get(poolName));
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
		
	public Connection getConnection(){
		Connection conn = null;
		try {			
			conn = makeDBConnection(this.getConnParam());
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return conn;
	}
	
	private static Connection makeDBConnection(ConnectionParameters param) throws SQLException {
        Connection conn = null;
        try {
            Class.forName(param.getDriver());                                    
            //conn = DriverManager.getConnection(param.getUrl(), param.getUser(), param.getPassword());
            Properties properties = new Properties();
            properties.put("SET character_set_results","UTF-8");
            properties.put("user", param.getUser());
            properties.put("password", param.getPassword());
            conn = DriverManager.getConnection(param.getUrl(), properties);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return conn;
    }

    public void releaseConnection(Connection conn, PreparedStatement preStmt) {
        try {
            if (preStmt != null)  preStmt.close();
            if (conn != null)  conn.close();
            if (conn == null || conn.isClosed()) return;            
        } catch (SQLException e) {}
    }

    public void releaseConnection(Connection conn, PreparedStatement preStmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
        } catch (SQLException e) {}

        releaseConnection(conn, preStmt);
    }

}
